package com.socialsoftware.adapter;

import android.content.Context;
import android.text.format.DateUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.socialsoftware.R;
import com.socialsoftware.model.FriendRequest;

import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Locale;

/**
 * 好友请求列表适配器
 */
public class FriendRequestAdapter extends RecyclerView.Adapter<FriendRequestAdapter.ViewHolder> {
    
    private final List<FriendRequest> friendRequests;
    private final Context context;
    private final OnRequestActionListener listener;
    
    // 状态常量
    public static final String STATUS_PENDING = "PENDING";
    public static final String STATUS_ACCEPTED = "ACCEPTED";
    public static final String STATUS_REJECTED = "REJECTED";
    public static final String STATUS_BLOCKED = "BLOCKED";
    
    // 日期格式化
    private final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault());
    
    public FriendRequestAdapter(Context context, List<FriendRequest> friendRequests, OnRequestActionListener listener) {
        this.context = context;
        this.friendRequests = friendRequests;
        this.listener = listener;
    }
    
    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.item_friend_request, parent, false);
        return new ViewHolder(view);
    }
    
    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        FriendRequest request = friendRequests.get(position);
        
        // 设置用户信息
        holder.tvName.setText(request.getRequesterName());
        holder.tvMessage.setText(request.getRequesterNote());
        
        // 设置头像
        // TODO: 使用图片加载库加载头像
        try {
            int resourceId = context.getResources().getIdentifier(
                request.getRequesterAvatar(), "drawable", context.getPackageName());
            if (resourceId != 0) {
                holder.ivAvatar.setImageResource(resourceId);
            } else {
                // 使用默认头像
                holder.ivAvatar.setImageResource(R.drawable.avatar_default);
            }
        } catch (Exception e) {
            // 如果加载失败，使用默认头像
            holder.ivAvatar.setImageResource(R.drawable.avatar_default);
        }
        
        // 设置时间
        if (request.getCreatedAt() != null) {
            // 如果时间在24小时内，显示相对时间，否则显示具体日期
            long timestamp = request.getCreatedAt().getTime();
            if (System.currentTimeMillis() - timestamp < 24 * 60 * 60 * 1000) {
                holder.tvTime.setText(DateUtils.getRelativeTimeSpanString(timestamp));
            } else {
                holder.tvTime.setText(dateFormat.format(request.getCreatedAt()));
            }
        }
        
        // 根据状态显示不同的UI
        updateUIByStatus(holder, request);
        
        // 设置点击事件
        holder.btnAccept.setOnClickListener(v -> {
            if (listener != null) {
                listener.onAcceptRequest(request);
            }
        });
        
        holder.btnReject.setOnClickListener(v -> {
            if (listener != null) {
                listener.onRejectRequest(request);
            }
        });
        
        holder.btnMore.setOnClickListener(v -> {
            if (listener != null) {
                listener.onMoreOptions(request, v);
            }
        });
    }
    
    @Override
    public int getItemCount() {
        return friendRequests.size();
    }
    
    /**
     * 根据请求状态更新UI
     */
    private void updateUIByStatus(ViewHolder holder, FriendRequest request) {
        String status = request.getStatus();
        
        if (STATUS_PENDING.equals(status)) {
            // 待处理状态，显示操作按钮
            holder.actionButtons.setVisibility(View.VISIBLE);
            holder.tvStatus.setVisibility(View.GONE);
        } else {
            // 其他状态，隐藏操作按钮，显示状态文本
            holder.actionButtons.setVisibility(View.GONE);
            holder.tvStatus.setVisibility(View.VISIBLE);
            
            switch (status) {
                case STATUS_ACCEPTED:
                    holder.tvStatus.setText("已添加");
                    holder.tvStatus.setTextColor(context.getResources().getColor(android.R.color.holo_green_dark));
                    break;
                case STATUS_REJECTED:
                    holder.tvStatus.setText("已拒绝");
                    holder.tvStatus.setTextColor(context.getResources().getColor(android.R.color.darker_gray));
                    break;
                case STATUS_BLOCKED:
                    holder.tvStatus.setText("已拉黑");
                    holder.tvStatus.setTextColor(context.getResources().getColor(android.R.color.holo_red_dark));
                    break;
            }
        }
    }
    
    /**
     * 更新好友请求状态
     */
    public void updateRequestStatus(Long requestId, String newStatus) {
        for (int i = 0; i < friendRequests.size(); i++) {
            FriendRequest request = friendRequests.get(i);
            if (request.getId().equals(requestId)) {
                request.setStatus(newStatus);
                notifyItemChanged(i);
                break;
            }
        }
    }
    
    /**
     * ViewHolder类
     */
    static class ViewHolder extends RecyclerView.ViewHolder {
        ImageView ivAvatar;
        TextView tvName;
        TextView tvMessage;
        TextView tvTime;
        Button btnAccept;
        Button btnReject;
        ImageButton btnMore;
        TextView tvStatus;
        LinearLayout actionButtons;
        
        ViewHolder(View itemView) {
            super(itemView);
            ivAvatar = itemView.findViewById(R.id.iv_avatar);
            tvName = itemView.findViewById(R.id.tv_name);
            tvMessage = itemView.findViewById(R.id.tv_message);
            tvTime = itemView.findViewById(R.id.tv_time);
            btnAccept = itemView.findViewById(R.id.btn_accept);
            btnReject = itemView.findViewById(R.id.btn_reject);
            btnMore = itemView.findViewById(R.id.btn_more);
            tvStatus = itemView.findViewById(R.id.tv_status);
            actionButtons = itemView.findViewById(R.id.action_buttons);
        }
    }
    
    /**
     * 好友请求操作监听器接口
     */
    public interface OnRequestActionListener {
        void onAcceptRequest(FriendRequest request);
        void onRejectRequest(FriendRequest request);
        void onMoreOptions(FriendRequest request, View anchorView);
    }
} 